import modelExtend from 'dva-model-extend'
import api from 'api'
const { pathToRegexp } = require("path-to-regexp")
import { pageModel } from 'utils/model'

const { createConfig,updateConfig,deleteConfig,getConfig,queryConfigList,queryConfigGroupList } = api

export default modelExtend(pageModel, {
  namespace: 'config',

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathToRegexp('/config').exec(location.pathname)) {
          console.log(location.query)
          let payload = location.query || {groupKey: "public", page: 1, pageSize: 10 }
          dispatch({
            type: 'query',
            payload: {
              ...payload,
            },
          })
        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const groupData = yield call(queryConfigGroupList)
      const data = yield call(queryConfigList, payload)
      if (data.success && groupData.success) {
        yield put({
          type: 'queryConfigSuccess',
          payload: {
            list: data.payload.list,
            groupList: groupData.payload,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.payload.total,
            },
          },
        })
      } else {
        throw data
      }
    },

    *update({payload}, {call, put}) {
      const r = yield call(updateConfig, payload)
      if(r.success) {
        yield put({ type: 'hideModal'})
      } else {
        throw r
      }
    },

    *delete({payload}, {call, put}) {
      console.log(payload)
      const r = yield call(deleteConfig, {id: payload})
      if(r.success) {
        //nothing todo
      } else {
        throw r
      }
    }
  },

  reducers: {
    //查询OK
    queryConfigSuccess(state, { payload }) {
      const { list, pagination, groupList } = payload
      return {
        ...state,
        list,
        groupList,
        pagination: {
          ...state.pagination,
          ...pagination,
        },
      }
    },

    //显示编辑框
    showModal(state, {payload}) {
      return {...state, ...payload, modalVisible: true}
    },

    //隐藏编辑框
    hideModal(state) {
      return {...state, modalVisible: false}
    },
  },
})
